package gwtappcontainer.server.apis.insight;

import static gwtappcontainer.server.apis.insight.OfyService.ofy;
import gwtappcontainer.server.DatastoreNamespaces;
import gwtappcontainer.server.apis.APIException;
import gwtappcontainer.server.apis.security.GateKeeper;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.insight.Center;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.Key;

class CenterRepository {	
	
	private final static String NAMESPACE = DatastoreNamespaces.INSIGHT;
	
	static ArrayList<Center> getAll() {
		
		NamespaceManager.set(NAMESPACE);		
		List<CenterEntity> entities = ofy().load().type(CenterEntity.class).list();
		
		ArrayList<Center> props = new ArrayList<Center>();
		
		for (CenterEntity entity : entities) {
			props.add(entity.toProp());
		}
		
		return props;
	}
	
	static Key<CenterEntity> getKeyFromName(String centerName) {
		centerName = centerName.toLowerCase();
		NamespaceManager.set(NAMESPACE);
		Key<CenterEntity> key = ofy().load().type(CenterEntity.class)
				.filter("name", centerName).first().getKey();				
		
		return key;				
	}		
	
	static Center getPropFromName(String centerName) {
		centerName = centerName.toLowerCase();
		CenterEntity entity = ofy().load().type(CenterEntity.class)
				.filter("name", centerName).first().get();
		
		if (entity == null)
			return null;
		
		return entity.toProp();				
	}
			
	static Center add(String name, String login) {
		
		GateKeeper.ensurePrivilege(login, Privileges.EDIT_CENTER);
		
		Key<CenterEntity> existing = getKeyFromName(name);
		
		if (existing != null)
			throw new APIException(Status.ERROR_RESOURCE_ALREADY_EXISTS, 
					"Center [" + name + "] already exists");				
		
		CenterEntity entity = new CenterEntity();
		entity.name = name.toLowerCase();
		
		NamespaceManager.set(NAMESPACE);
		ofy().save().entity(entity).now();
				
		return entity.toProp();		
	}
	
	static Center update(String newName, String existingName) {
							
		NamespaceManager.set(NAMESPACE);
		List<CenterEntity> all = ofy().load().type(CenterEntity.class).list();
		
		//throw exception if existing name does not already exist
		CenterEntity entity = null;
		for (CenterEntity e : all) {
			if (e.name.equalsIgnoreCase(existingName))
				entity = e;
		}
		
		if (entity == null)
			throw new APIException(Status.ERROR_RESOURCE_DOES_NOT_EXIST, 
					"No center found with name [" + existingName + "]");
		
		entity.name = newName.toLowerCase();
		ofy().save().entity(entity).now();
		
		return entity.toProp();
	}
}
